package www.hz.domain.strategy.service.rule.filter.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import www.hz.domain.strategy.model.entity.RuleActionEntity;
import www.hz.domain.strategy.model.entity.RuleMatterEntity;
import www.hz.domain.strategy.model.vo.RuleLogicCheckTypeVO;
import www.hz.domain.strategy.repository.IStrategyRepository;
import www.hz.domain.strategy.service.annotation.LogicStrategy;
import www.hz.domain.strategy.service.rule.filter.ILogicFilter;
import www.hz.domain.strategy.service.rule.filter.factory.DefaultLogicFactory;
import www.hz.types.common.Constants;

import javax.annotation.Resource;
import java.util.*;

/**
 * @className: RuleWeightLogicFilter
 * @Description: 权重过滤器
 * @version: v1.８.0
 * @author: hz
 * @date: 2025/3/13 11:07
 */
@Component
@Slf4j
@LogicStrategy(logicMode = DefaultLogicFactory.LogicModel.RULE_WIGHT)
public class RuleWeightLogicFilter implements ILogicFilter<RuleActionEntity.RaffleBeforeEntity> {
    @Resource
    private IStrategyRepository repository;
    public Long userScore = 4500L;
    /**
     * 权重规则过滤；
     * 1. 权重规则格式；4000:102,103,104,105 5000:102,103,104,105,106,107 6000:102,103,104,105,106,107,108,109
     * 2. 解析数据格式；判断哪个范围符合用户的特定抽奖范围
     *
     * @param ruleMatterEntity 规则物料实体对象
     * @return 规则过滤结果
     */
    @Override
    public RuleActionEntity<RuleActionEntity.RaffleBeforeEntity> filter(RuleMatterEntity ruleMatterEntity) {
      //1.根据用户ID查询用户的积分值，目前我们先写死为固定的值，后续需要从数据库中查询
        String userId = ruleMatterEntity.getUserId();
        Long strategyId = ruleMatterEntity.getStrategyId();
        String ruleValue = repository.queryStrategyRuleValue(ruleMatterEntity.getStrategyId(),
                ruleMatterEntity.getAwardId(), ruleMatterEntity.getRuleModel());
        Map<Long,String> analyticalValueGroup=getAnalyticalValueGroup(ruleValue);
        //2.找出最小符合的值，也就是【4500 积分，能找到 4000:102,103,104,105】、【5000 积分，能找到 5000:102,103,104,105,106,107】
        List<Long> analyticalSortedKeys=new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys,Comparator.reverseOrder());
        Long nextValue=analyticalSortedKeys.stream().filter(key->userScore>=key).findFirst().orElse(null);
        if(nextValue!=null){
            return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                    .code(RuleLogicCheckTypeVO.TAKE_OVER.getCode())
                    .info(RuleLogicCheckTypeVO.TAKE_OVER.getInfo())
                    .ruleModel(DefaultLogicFactory.LogicModel.RULE_WIGHT.getCode())
                    .data(RuleActionEntity.RaffleBeforeEntity.builder()
                            .ruleWeightValueKey(analyticalValueGroup.get(nextValue))
                            .strategyId(ruleMatterEntity.getStrategyId())
                            .build())
                    .build();
        }


        return RuleActionEntity.<RuleActionEntity.RaffleBeforeEntity>builder()
                .code(RuleLogicCheckTypeVO.ALLOW.getCode())
                .info(RuleLogicCheckTypeVO.ALLOW.getInfo())
                .build();
    }

    private Map<Long, String> getAnalyticalValueGroup(String ruleValue) {
          String[] ruleValueGroups = ruleValue.split(Constants.SPACE);
        Map<Long, String> map=new HashMap<>();
        for (String ruleValueGroup : ruleValueGroups) {
            String[] ruleValueGroupAttr=ruleValueGroup.split(Constants.COLON);
            if (ruleValueGroupAttr.length != 2) throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueGroup);
            map.put(Long.valueOf(ruleValueGroupAttr[0]),ruleValueGroup);
        }
        return map;
    }


}